package com.tiger.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tiger.utils.DateTimeUtils;
import com.tiger.utils.RedisUtils;
import com.tiger.utils.Sync2ElasticsearchUtils;
import com.tiger.utils.UpdateUtils;
import com.tiger.mapper.adminPage.*;
import com.tiger.mapper.base.*;
import com.tiger.pojo.adminPage.*;
import com.tiger.pojo.base.*;
import io.minio.*;
import io.minio.http.Method;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.sql.Timestamp;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author HuXuehao (StudiousTiger)
 * @desc 这个类的作用是
 * @date 2022/2/13
 */
@Slf4j
@RestController
public class    AdminPageController {
    @Autowired
    private AdminCountsForAllMapper adminCountsForAllMapper;
    @Autowired
    private AdminPageReportInfoMapper adminPageReportInfoMapper;
    @Autowired
    private AdminPageUserManageCardsMapper adminPageUserManageCardsMapper;
    @Autowired
    private SystemNewsMapper systemNewsMapper;
    @Autowired
    private AdvertisementMapper advertisementMapper;
    @Autowired
    private UserIncreaseInfoMapper userIncreaseInfoMapper;
    @Autowired
    private UserActiveInfoMapper userActiveInfoMapper;
    @Autowired
    private UserWorksIncreaseInfoMapper userWorksIncreaseInfoMapper;
    @Autowired
    private UserGenderInfoMapper userGenderInfoMapper;
    @Autowired
    private UserCodeAgeInfoMapper userCodeAgeInfoMapper;
    @Autowired
    private ReportTypeInfoMapper reportTypeInfoMapper;
    @Autowired
    private ExcelMapper excelMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private IgnoreReportMapper ignoreReportMapper;
    @Autowired
    private ReportedClassifyMapper reportedClassifyMapper;
    @Autowired
    private ErrorMapper errorMapper;
    @Autowired
    private QuestionMapper questionMapper;
    @Autowired
    private ErrorReplyMapper errorReplyMapper;
    @Autowired
    private QuestionReplyMapper questionReplyMapper;
    @Autowired
    private EntryMapper entryMapper;
    @Autowired
    private MinioClient minioClient;
    @Autowired
    private RedisUtils redisUtil;
    @Autowired
    private Sync2ElasticsearchUtils sync2EsUtils;

    @Value("${minio.bucketNameOfMdFile}")
    private String bucketNameOfMdFile;
    @Value("${minio.bucketNameOfAD}")
    private String bucketNameOfAD;
    @Value("${minio.bucketName}")
    private String bucketName;
    @Value("${minio.bucketNameOfXls}")
    private String bucketNameOfXls;
    @Value("${minio.endPoint}")
    private String endPoint;
    @Value("${minio.bucketNameOfTips}")
    private String bucketNameOfTips;
    @Value("${minio.bucketNameOfMdPicture}")
    private String bucketNameOfMdPicture;

    @Autowired
    private UpdateUtils updateUtils;

    /**
     * 获取的adminPage中“数据”的顶部的四个信息
     * @return
     */
    @RequestMapping(value = "/adminPage/getCountsForAll",name = "获取全站作品数量/admin")
    public String getAdminCountsForAll(){
        try{
            List<AdminCountsForAll> res = adminCountsForAllMapper.selectList(null);
            return JSON.toJSONString(res);
        }catch (Exception e){
            log.error(e.toString());
            return "false";
        }
    }

    /**
     * 获取页码
     * @param classify
     * @return
     */
    @RequestMapping(value = "/adminPage/getPages/{classify}",name = "获取页码/admin")
    public Long getPages(@PathVariable String classify) {
        Long allPages = null;

        Page<AdminPageReportInfo> adminPageReportInfoPage;
        Page<AdminPageUserManageCards> adminPageUserManageCardsPage;

        QueryWrapper<Excel> wrapper;
        Page<Excel> excelPage;

        QueryWrapper<Entry> entryWrapper;
        Page<Entry> entryPage;
        switch (classify) {
            case "adminPageReportInfo" :
                adminPageReportInfoPage = new Page<>(1, 20);  // 分页，一页20个结果
                adminPageReportInfoPage = adminPageReportInfoMapper.selectPage(adminPageReportInfoPage, null);
                allPages = adminPageReportInfoPage.getPages();
                break;
            case "adminErrorUser":
                adminPageUserManageCardsPage = new Page<>(1, 20);  // 分页，一页20个结果
                adminPageUserManageCardsPage = adminPageUserManageCardsMapper.selectPage(adminPageUserManageCardsPage, null);
                allPages = adminPageUserManageCardsPage.getPages();
                break;
            case "allExcel":
                excelPage = new Page<>(1, 20);  // 分页，一页20个结果
                excelPage = excelMapper.selectPage(excelPage, null);
                allPages = excelPage.getPages();
                break;
            case "userActive":
                wrapper = new QueryWrapper<>();
                wrapper.eq("excel_classify","userActive");
                excelPage = new Page<>(1, 20);  // 分页，一页20个结果
                excelPage = excelMapper.selectPage(excelPage, null);
                allPages = excelPage.getPages();
                break;
            case "userIncrease":
                wrapper = new QueryWrapper<>();
                wrapper.eq("excel_classify","userIncrease");
                excelPage = new Page<>(1, 20);  // 分页，一页20个结果
                excelPage = excelMapper.selectPage(excelPage, null);
                allPages = excelPage.getPages();
                break;
            case "worksIncrease":
                wrapper = new QueryWrapper<>();
                wrapper.eq("excel_classify","worksIncrease");
                excelPage = new Page<>(1, 20);  // 分页，一页20个结果
                excelPage = excelMapper.selectPage(excelPage, null);
                allPages = excelPage.getPages();
                break;
            case "reportedType":
                wrapper = new QueryWrapper<>();
                wrapper.eq("excel_classify","reportedType");
                excelPage = new Page<>(1, 20);  // 分页，一页20个结果
                excelPage = excelMapper.selectPage(excelPage, null);
                allPages = excelPage.getPages();
                break;
            case "userCodeAge":
                wrapper = new QueryWrapper<>();
                wrapper.eq("excel_classify","userCodeAge");
                excelPage = new Page<>(1, 20);  // 分页，一页20个结果
                excelPage= excelMapper.selectPage(excelPage, null);
                allPages = excelPage.getPages();
                break;
            case "userGender":
                wrapper = new QueryWrapper<>();
                wrapper.eq("excel_classify","userGender");
                excelPage = new Page<>(1, 20);  // 分页，一页20个结果
                excelPage = excelMapper.selectPage(excelPage, null);
                allPages = excelPage.getPages();
                break;
            case "translate":
                entryWrapper = new QueryWrapper<>();
                entryWrapper.eq("entry_type","translate");
                entryPage = new Page<>(1, 20);  // 分页，一页20个结果
                entryPage = entryMapper.selectPage(entryPage, null);
                allPages = entryPage.getPages();
                break;
            case "baike":
                entryWrapper = new QueryWrapper<>();
                entryWrapper.eq("entry_type","baike");
                entryPage = new Page<>(1, 20);  // 分页，一页20个结果
                entryPage = entryMapper.selectPage(entryPage, null);
                allPages = entryPage.getPages();
                break;
            default:
                break;
        }

        return allPages;
    }

    /**
     * 获取adminPage中“消息”所需的信息
     * @return
     */
    @RequestMapping(value = "/adminPage/getReportInfo/{currentPage}",name = "获取举报信息/admin")
    public String getAdminReportInfo(@PathVariable int currentPage){
        Page<AdminPageReportInfo> page = new Page<>(currentPage, 20);
        QueryWrapper<AdminPageReportInfo> wrapper = new QueryWrapper<>();
        try{
            Page<AdminPageReportInfo> adminPageReportInfoPage = adminPageReportInfoMapper.selectPage(page, wrapper);
            List<AdminPageReportInfo> adminPageReportInfos = adminPageReportInfoPage.getRecords();

            if (adminPageReportInfos.size()!=0){
                for (AdminPageReportInfo adminPageReportInfo : adminPageReportInfos) {
                    // 获取被举报的文本的地址对应的 minio 中文件的文本，并重写入 reportedContextAddr 中
                    adminPageReportInfo.setReportedContextAddr(
                            getMarkdownOfText(adminPageReportInfo.getReportedContextAddr())
                    );
                }
                return JSON.toJSONString(adminPageReportInfos);
            }else{
                return "empty";
            }
        }catch (Exception e){
            log.error(e.toString());
            return "false";
        }
    }

    private String getMarkdownOfText(String fileName) {
        try {
            // 从 minio 中获取文件流
            InputStream inputStream = minioClient.getObject(
                    GetObjectArgs.builder()
                            .bucket(bucketNameOfMdFile)
                            .object(fileName)
                            .build());

            // 将 InputStream 转换为 String
            String res = new BufferedReader(new InputStreamReader(inputStream))
                                    .lines().collect(Collectors.joining(System.lineSeparator()));

            return updateUtils.updateMDOfImgURL(res, bucketNameOfMdPicture);
        } catch (Exception e) {
            log.error(e.toString());
            return "false";
        }
    }
    /**
     * 忽略举报信息
     * @param reportId  举报ID
     * @return
     */
    @RequestMapping(value = "/adminPage/ignoreReport/{reportId}",name = "忽略被举报内容/admin")
    public String ignoreReport(@PathVariable String reportId){
        try {
            // 插入
            IgnoreReport ignoreReport = new IgnoreReport();
            ignoreReport.setReportedId(reportId);
            ignoreReport.setDate(DateTimeUtils.currentDateTime2SQLTimestamp());

            int res = ignoreReportMapper.insert(ignoreReport);
            if (res ==1) {
                return "true";
            } else  {
                return "false";
            }
        } catch (Exception e) {
            log.error(e.toString());
            return "false";
        }
    }

    /**
     * 删除举报信息对应的举报内容
     * @param reportId
     * @param reportedContextId
     * @return
     */
    @RequestMapping(value = "/adminPage/deleteReportedContext/{reportId}/{reportedContextId}",name = "删除被举报内容/admin")
    public String deleteReportedContext(@PathVariable String reportId,@PathVariable String reportedContextId){
        try {
            // 将要处理的内容插入到
            IgnoreReport ignoreReport = new IgnoreReport();
            ignoreReport.setReportedId(reportId);
            ignoreReport.setDate(DateTimeUtils.currentDateTime2SQLTimestamp());
            int insert = ignoreReportMapper.insert(ignoreReport);
            if (insert == 1) {
                // 根据 reportId 获取类型
                QueryWrapper<ReportedClassify> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("reported_id",reportedContextId);
                String classify = reportedClassifyMapper.selectList(queryWrapper).get(0).getClassify();
                int delete = 0;
                if ("error".equals(classify)) {
                    delete = errorMapper.deleteById(reportedContextId);
                    if (delete ==1 ) {
                        sync2EsUtils.deleteOpt(reportedContextId);  // 同步es
                    }
                } else if ("question".equals(classify)) {
                    delete = questionMapper.deleteById(reportedContextId);
                    if (delete ==1 ) {
                        sync2EsUtils.deleteOpt(reportedContextId);  // 同步es
                    }
                } else if ("error_reply".equals(classify)) {
                    delete = errorReplyMapper.deleteById(reportedContextId);
                } else if ("error_reply".equals(classify)) {
                    delete = questionReplyMapper.deleteById(reportedContextId);
                }
                if (delete == 1) {
                    return "true";
                } else {
                    // 删除原本插入到 IgnoreReport 中的内容
                    Map<String, Object> map = new HashMap<>();
                    map.put("reported_id",reportId);
                    ignoreReportMapper.deleteByMap(map);
                    return "false";
                }
            } else {
                return "false";
            }

        } catch (Exception e) {
            log.error(e.toString());
            return "false";
        }
    }

    /**
     * 获取adminPage中“用户”所需的信息
     * @param currentPage
     * @return
     */
    @RequestMapping(value = "/adminPage/getAdminUserManage/{currentPage}",name = "获取被举报用户信息/admin")
    public String getAdminUserManage(@PathVariable int currentPage){
        Page<AdminPageUserManageCards> page = new Page<>(currentPage, 20);
        QueryWrapper<AdminPageUserManageCards> wrapper = new QueryWrapper<>();
        try{
            Page<AdminPageUserManageCards> adminPageUserManageCardsPage = adminPageUserManageCardsMapper.selectPage(page, wrapper);
            List<AdminPageUserManageCards> res = adminPageUserManageCardsPage.getRecords();
            if (res.size()!=0){
                for (AdminPageUserManageCards re : res) {
                    re.setUserHeadPhotoPath(
                            updateUtils.getNewHeadPhotoURL(re.getUserHeadPhotoPath())
                    );
                }
                return JSON.toJSONString(res);
            }else{
                return "empty";
            }
        }catch (Exception e){
            log.error(e.toString());
            return "false";
        }
    }

    /**
     * 发布广告
     * @param file  文件
     * @param classify  分类
     * @param order 序号
     * @return
     */
    @RequestMapping(value = "/adminPage/addAdvertisement/{classify}/{order}",name = "发布广告/admin")
    public String addiAdvertisement(@RequestParam(name = "file", required = false) MultipartFile file,
                                    @PathVariable String classify,@PathVariable int order){
        if (file == null){
            return "false";
        }
        try {
            QueryWrapper<Advertisement> wrapper = new QueryWrapper<>();
            wrapper.eq("advertisement_classify",classify);
            wrapper.eq("advertisement_order",order);
            List<Advertisement> advertisements = advertisementMapper.selectList(wrapper);
            String advertisementID = advertisements.get(0).getAdvertisementId();
            String fileName = advertisementID+".jpg";

            String url = putImgAndGetUrlOfImg(file, fileName, advertisementID);

            // 将图片存到数据库中
            UpdateWrapper<Advertisement> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("advertisement_id",advertisementID);
            updateWrapper.set("advertisement_addr",fileName);
            advertisementMapper.update(null,updateWrapper);

            return url;
        } catch (Exception e) {
            log.error(e.toString());
            return "false";
        }
    }
    // 将图片推送到MINIO,获取URL地址
    private String putImgAndGetUrlOfImg(MultipartFile file, String fileName, String advertisementID){
        InputStream in = null;
        try {
            // 判断目标 bucket 是否存在
            boolean exit = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketNameOfAD).build());
            if (!exit){
                // 创建名为 bucketName 的 bucket
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketNameOfAD).build());
            }
            in = file.getInputStream();
            // 上传图片
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(bucketNameOfAD)
                            .object(fileName)
                            .stream(in,file.getSize(),-1)
                            .build()
            );

            //获取头像路径
            String url = minioClient.getPresignedObjectUrl(
                    GetPresignedObjectUrlArgs.builder()
                            .method(Method.GET)
                            .bucket(bucketNameOfAD)
                            .object(fileName)
                            .build());
            return url;
        } catch (Exception e) {
            log.error(e.toString());
            return "false";
        } finally {
            // 关闭流
            if (in != null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 获取不同类型的广告
     * @param classify
     * @return
     */
    @RequestMapping(value = "/adminPage/getADPhoto/{classify}", name = "获取广告图片/admin")
    public String getADPhoto(@PathVariable String classify){
        QueryWrapper<Advertisement> wrapper = new QueryWrapper<>();
        wrapper.eq("advertisement_classify",classify);
        try {
            List<Advertisement> advertisements = advertisementMapper.selectList(wrapper);
            for (Advertisement advertisement : advertisements) {
                advertisement.setAdvertisementAddr(
                        updateUtils.getNewHeadPhotoURL(advertisement.getAdvertisementAddr())
                );
            }
            return JSON.toJSONString(advertisements);
        } catch (Exception e){
            e.printStackTrace();
            log.error(e.toString());
            return "false";
        }
    }

    /**
     * 获取用户增长情况
     * @return
     */
    @RequestMapping(value = "/adminPage/getUserIncreaseInfo", name = "获取用户增长情况/admin")
    public String getUserIncreaseInfo(){
        try{
            List<UserIncreaseInfo> res = userIncreaseInfoMapper.selectList(null);
            return JSON.toJSONString(res);
        }catch (Exception e){
            log.error(e.toString());
            return "false";
        }
    }

    /**
     * 获取用户活跃度情况
     * @return
     */
    @RequestMapping(value = "/adminPage/getUserActiveInfo", name = "获取用户活跃度情况/admin")
    public String getUserActiveInfo(){
        try{
            List<UserActiveInfo> res = userActiveInfoMapper.selectList(null);
            return JSON.toJSONString(res);
        }catch (Exception e){
            log.error(e.toString());
            return "false";
        }
    }

    /**
     * 获取用户作品增长信息
     * @return
     */
    @RequestMapping(value = "/adminPage/getUserWorksIncreaseInfo", name = "获取用户作品增长信息/admin")
    public String getUserWorksIncreaseInfo(){
        try{
            List<UserWorksIncreaseInfo> res = userWorksIncreaseInfoMapper.selectList(null);
            return JSON.toJSONString(res);
        }catch (Exception e){
            log.error(e.toString());
            return "false";
        }
    }

    /**
     * 获取用户的性别比例信息
     * @return
     */
    @RequestMapping(value = "/adminPage/getUserGenderInfo", name = "获取用户的性别比例信息/admin")
    public String getUserGenderInfo(){
        try{
            List<UserGenderInfo> res = userGenderInfoMapper.selectList(null);
            return JSON.toJSONString(res);
        }catch (Exception e){
            log.error(e.toString());
            return "false";
        }
    }

    /**
     * 获取用户码龄比例信息
     * @return
     */
    @RequestMapping(value = "/adminPage/getUserCoderAgeInfo", name = "获取用户码龄比例信息/admin")
    public String getUserCoderAgeInfo(){
        try{
            List<UserCodeAgeInfo> res = userCodeAgeInfoMapper.selectList(null);
            return JSON.toJSONString(res);
        }catch (Exception e){
            log.error(e.toString());
            return "false";
        }
    }

    /**
     * 获取举报类型信息
     * @return
     */
    @RequestMapping(value = "/adminPage/getReportTypeInfo", name = "获取举报类型信息/admin")
    public String getReportTypeInfo(){
        try{
            List<ReportTypeInfo> res = reportTypeInfoMapper.selectList(null);
            return JSON.toJSONString(res);
        }catch (Exception e){
            log.error(e.toString());
            return "false";
        }
    }

    /**
     * 推送消息
     * @param news
     * @return
     */
    @RequestMapping(value = "/adminPage/publishNews/{news}", name = "推送消息/admin")
    public String publishNews(@PathVariable String news){
        SystemNews systemNews = JSON.parseObject(news, SystemNews.class);
        int res;
        // 即时发送时，设置当前时间
        if ("true".equals(systemNews.getSystemNewsNowPublish())){
            systemNews.setSystemNewsTimingPublishDate(DateTimeUtils.currentDateTime2SQLTimestamp());
            res = systemNewsMapper.insert(systemNews);
            if (res==1){
                return "trueForNow";
            } else {
                return "falseForNow";
            }
        }else {
            res = systemNewsMapper.insert(systemNews);
            if (res==1){
                return "true";
            } else {
                return "false";
            }
        }
    }

    /**
     * 获取所有excel文件名和下载路径
     * @return
     */
    @RequestMapping(value = "/adminPage/getAllExcel/{currentPage}", name = "获取所有excel文件名和下载路径/admin")
    public String getAllNameOfExcel(@PathVariable int currentPage){
        Page<Excel> page = new Page<>(currentPage, 20);
        QueryWrapper<Excel> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("excel_datetime");
        wrapper.eq("excel_tag",0);
        try{
            Page<Excel> pages = excelMapper.selectPage(page, wrapper);
            List<Excel> res = pages.getRecords();
            if (res.size()!=0){
                for (Excel re : res) {
                    re.setExcelDownloadUrl(
                            updateUtils.getExcelURL(re.getExcelDownloadUrl())
                    );
                }
                return JSON.toJSONString(res);
            }else{
                return "empty";
            }
        }catch (Exception e){
            log.error(e.toString());
            return "false";
        }
    }


    /**
     * 获取不同分类的excel文件名和下载路径
     * @param classify
     * @param currentPage
     * @return
     */
    @RequestMapping(value = "/adminPage/getExcel/{classify}/{currentPage}", name = "获取不同分类的excel文件名和下载路径/admin")
    public String getAllNameOfExcel(@PathVariable String classify,@PathVariable int currentPage){
        Page<Excel> page = new Page<>(currentPage, 20);
        QueryWrapper<Excel> wrapper = new QueryWrapper<>();
        wrapper.eq("excel_classify",classify);
        wrapper.orderByDesc("excel_datetime");
        wrapper.eq("excel_tag",0);
        try{
            Page<Excel> pages = excelMapper.selectPage(page, wrapper);
            List<Excel> res = pages.getRecords();
            if (res.size()!=0){
                for (Excel re : res) {
                    re.setExcelDownloadUrl(
                            updateUtils.getExcelURL(
                                    re.getExcelDownloadUrl()
                            )
                    );
                }
                return JSON.toJSONString(res);
            }else{
                return "empty";
            }
        }catch (Exception e){
            log.error(e.toString());
            return "false";
        }
    }

    /**
     * 获取词条信息
     * @param type
     * @param currentPage
     * @return
     */
    @RequestMapping(value = "/adminPage/getEntry/{type}/{currentPage}", name = "获取词条信息/admin")
    public String getEntry(@PathVariable String type,@PathVariable int currentPage){
        Page<Entry> page = new Page<>(currentPage, 20);
        QueryWrapper<Entry> wrapper = new QueryWrapper<>();
        wrapper.eq("entry_type",type);
        wrapper.orderByDesc("entry_datetime");
        try{
            Page<Entry> pages = entryMapper.selectPage(page, wrapper);
            List<Entry> res = pages.getRecords();
            if (res.size()!=0){
                for (Entry re : res) {
                    re.setEntryDownloadUrl(
                            updateUtils.getExcelURL(
                                    re.getEntryDownloadUrl()
                            )
                    );
                }
                return JSON.toJSONString(res);
            }else{
                return "empty";
            }
        }catch (Exception e){
            log.error(e.toString());
            return "false";
        }
    }


    /**
     * 处理违规用户
     * @param userID
     * @param type    处理类型（封号、禁言...）
     * @param duration  处理时长
     * @return
     */
    @RequestMapping(value = "/adminPage/handleErrorUser/{userID}/{type}/{duration}", name = "处理违规用户/admin")
    public String handleErrorUser(@PathVariable String userID, @PathVariable String type, @PathVariable String duration ){
        // 获取操作到期时间
        long optTime = Long.parseLong(duration);
        long time = DateTimeUtils.currentDateTime2SQLTimestamp().getTime();
        long resultTime = time + optTime;
        Timestamp timestamp = new Timestamp(resultTime);

        UpdateWrapper<User> wrapper = new UpdateWrapper<>();
        try {
            int res;
            // 封号
            if ("noLogin".equals(type)) {
                wrapper.eq("user_id", userID);
                wrapper.set("opt_time",timestamp);
                res = userMapper.update(null, wrapper);
            } else if ("noSpeak".equals(type)) {  // 禁言
                // 封号处理....
                return null;
            } else {  // 忽略
                wrapper.eq("user_id", userID);
                wrapper.set("opt_time",DateTimeUtils.currentDateTime2SQLTimestamp());
                res = userMapper.update(null, wrapper);
            }
            if (res == 1) {
                // 将操作完成后的用户打入IgnoreReport中
                IgnoreReport ignoreReport = new IgnoreReport();
                ignoreReport.setReportedId(userID);
                ignoreReport.setDate(DateTimeUtils.currentDateTime2SQLTimestamp());
                int insert = ignoreReportMapper.insert(ignoreReport);

                return insert == 1? "true" : "false";
            } else {
                return "false";
            }
        } catch (Exception e) {
            log.error(e.toString());
            return "false";
        }
    }

    @RequestMapping(value = "/adminPage/addDependencyTxt/", name = "上传名言警句/admin")
    public void addDependencyTxt(@RequestParam(name = "file", required = false) MultipartFile file){
        try {
            Set<String> tips = file2Set(file);
            if (tips != null) {
                uploadTxt(file);
                setUploadRedis(tips);
            }
        } catch (Exception e) {
            log.error(e.toString());
        }

    }
    // 将 MultipartFile 中的数据以一行为单位，保存到 set 中，并返回
    private Set<String> file2Set(MultipartFile file){
        InputStream is = null;
        InputStreamReader isr = null;
        BufferedReader bread = null;
        String data;
        try {
            is = file.getInputStream();
            isr = new InputStreamReader(is, "UTF-8");
            bread = new BufferedReader(isr);
            Set<String> tips = new HashSet<>();
            //以一行为单位进行读取
            while((data = bread.readLine()) != null) {
                tips.add(data);
            }
            return tips;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }finally {
            if (bread != null) {
                try {
                    bread.close();
                } catch (IOException e) {
                    log.error(e.toString());
                }
            }
            if (isr != null) {
                try {
                    isr.close();
                } catch (IOException e) {
                    log.error(e.toString());
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    log.error(e.toString());
                }
            }
        }
    }

    // 将 MultipartFile 文件上传到 minio, 并返回文件的 url
    private void  uploadTxt(MultipartFile file){
        String fileName = "tips.txt";
        InputStream in = null;
        try {
            // 判断目标 bucket 是否存在
            boolean exit = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketNameOfTips).build());
            if (!exit){
                // 创建名为 bucket
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketNameOfTips).build());
            }

            in = file.getInputStream();
            // 上传 txt 文件
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(bucketNameOfTips)
                            .object(fileName)
                            .stream(in,file.getSize(),-1)
                            .build()
            );
        } catch (Exception e) {
            log.error(e.toString());
        } finally {
            // 关闭流
            if (in != null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private static final String TIPS = "tips";
    // 将 set 中的元素存入到 redis 中
    private void setUploadRedis(Set<String> tips){
        try {
            for (String tip : tips) {
                redisUtil.sSet(TIPS, tip);
            }
        } catch (Exception e) {
            log.error(e.toString());
        }
    }

    /**
     * 获取 tips 文件的下载路径
     * @return
     */
    @RequestMapping(value = "/adminPage/getTipsFileDownloadUrl", name = "获取名言警句的下载路径/admin")
    public String getTipsFileDownloadUrl(){
        try {
            String url = minioClient.getPresignedObjectUrl(
                    GetPresignedObjectUrlArgs
                            .builder()
                            .method(Method.GET)
                            .bucket(bucketNameOfTips)
                            .object("tips.txt")
                            .build());
            return url == null ? "false" : url;
        } catch (Exception e) {
           log.error(e.toString());
           return "false";
        }
    }

}
